<template>
  <Transition
    enter-active-class="animate-slide-in"
    leave-active-class="animate-slide-out"
    @enter="afterEnter"
    v-bind="$attrs"
  >
    <div
      v-show="isVisible"
      class="outline-[4px] outline-[#fff] p-[4px] fixed bottom-[80px] right-5 w-[60%] sm:w-[408px] h-[500px] 2xl:h-[648px] bg-[#fff] rounded-[20px] z-[1000] box-shadow-[0px_4px_8px_0px_#00000014]"
    >
      <div
        class="flex flex-col h-full rounded-[20px] border-[1px] border-[#eeeef5] overflow-hidden"
      >
        <div
          class="h-[56px] px-6 py-4 flex justify-between items-center border-b border-[#eeeef5]"
          style="background-size: cover"
          :style="{ backgroundImage: `url(${BgImage})` }"
        >
          <h2 class="m-0">AI助手</h2>
          <button @click="handleClose" class="btn btn-sm btn-circle btn-ghost">
            <DeleteSvg class="w-5 h-5 text-[#5c5c5c]" :fontControlled="false" />
          </button>
        </div>
        <div
          class="flex-1 px-4 py-6 overflow-y-auto flex flex-col gap-3 bg-[#f6f7fa] text-sm"
          ref="chatMessagesRef"
        >
          <TransitionGroup name="message" tag="div" class="flex flex-col gap-y-[16px]">
            <div v-for="(message, index) in messages" :key="index" class="w-full">
              <!-- 普通消息显示 -->
              <div
                v-if="message.type !== 'agent-cards' && message.type !== 'mcp'"
                class="flex gap-x-2"
                :class="message.type === 'sent' ? 'flex-row-reverse' : 'flex-row'"
              >
                <div class="w-8 flex-shrink-0">
                  <UserAvatarSvg v-if="message.type === 'sent'" :fontControlled="false" filled />
                  <ChatAvatarSvg v-else :fontControlled="false" filled />
                </div>
                <div class="max-w-[calc(100%-2rem)]" :class="[message.type === 'sent' && 'flex flex-col items-end']">
                  <div
                    class="text-sm/5 py-[8px] px-[12px]"
                    :class="[
                      ['mermaid', 'received'].includes(message.type) &&
                        'bg-white rounded-tr-[8px] rounded-b-[8px] shadow-[0px_4px_8px_0px_#00000014]',
                      message.type === 'sent' && 'bg-[#eee7fd] rounded-l-[8px] rounded-br-[8px]',
                    ]"
                  >
                    <LoadingSvg
                      v-if="message.type === 'received' && message.loading"
                      class="size-[24px] text-[#713CEE]"
                      :fontControlled="false"
                    />
                    <template v-else>
                      <VueMarkdownRender :source="message.content" />
                    </template>
                  </div>
                  <div class="mt-[4px]">
                    <time class="text-xs opacity-24 ml-1">{{
                      formatTime(message.timestamp || Date.now())
                    }}</time>
                  </div>
                </div>
              </div>

              <!-- agent-card组件显示 -->
              <div v-if="message.type === 'agent-cards'" class="flex flex-col gap-3 pl-3">
                <a-timeline>
                  <a-timeline-item v-for="(agent, agentIndex) in message.agents" :key="agentIndex">
                    <AgentCard :agent="agent" :isGrouped="false" />
                  </a-timeline-item>
                </a-timeline>
                <LoadingSvg
                  v-if="message.agents?.length < agentData.length"
                  class="size-[24px] text-[#713CEE]"
                  :fontControlled="false"
                />
              </div>
              <div v-if="message.type === 'mcp'" class="flex flex-col gap-3 pl-3">
                <McpContent />
              </div>
            </div>
          </TransitionGroup>
        </div>
        <div class="flex border-t border-base-300 bg-base-100">
          <textarea
            ref="textareaRef"
            v-model="newMessage"
            class="textarea textarea-ghost focus:outline-none min-h-[52px] resize-none flex-1 placeholder:text-[#d6d6d6] placeholder:text-sm"
            placeholder="请输入"
            @keyup.enter="sendMessage"
          ></textarea>
          <div class="p-[8px]">
            <button
              @click="sendMessage"
              class="btn btn-primary rounded-[8px] size-[36px] p-[8px]"
              style="--color-primary: #713cee"
              :disabled="isLoading"
            >
              <img src="~/assets/icons/aircraft.png" class="size-[20px]" />
            </button>
          </div>
        </div>
      </div>
    </div>
  </Transition>
  <ClientOnly>
    <ChatPreviewDialog
      v-if="chatPreviewDialogVisible"
      ref="chatPreviewDialogRef"
      @close="closeChatPreviewDialog"
    />
  </ClientOnly>
  <MermaidDialog
    v-if="mermaidDialogVisible"
    :type="mermaidDialogType"
    ref="mermaidDialogRef"
    @close="closeMermaidDialog"
  />
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from "vue";
import ChatPreviewDialog from "./ChatPreviewDialog.vue";
import { chat } from "~/apis/index.client";
import ChatAvatarSvg from "~/assets/images/chat-avatar.svg";
import UserAvatarSvg from "~/assets/images/user-avatar.svg";
import BgImage from "~/assets/images/bg.png";
import DeleteSvg from "~/assets/icons/delete.svg";
import LoadingSvg from "~/assets/icons/loading.svg";
import MermaidDialog from "../mermaid/MermaidDialog.vue";
import { useCompanyStore } from "@/stores/company";
import AgentCard from "~/components/agent/agent-card.vue";
import McpContent from "../mcpTime/index.vue";
import VueMarkdownRender from "vue-markdown-render";
const companyStore = useCompanyStore();

const handleKeyDown = (e) => {
  if (e.key === "Escape") {
    handleClose();
  }
};

onMounted(() => {
  document.addEventListener("keydown", handleKeyDown);
});

onUnmounted(() => {
  document.removeEventListener("keydown", handleKeyDown);
});

const isVisible = defineModel("isVisible", {
  default: false,
});

const textareaRef = ref(null);

watch(isVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      textareaRef.value.focus();
    });
  }
});

const emit = defineEmits(["close"]);

const handleClose = () => {
  isVisible.value = false;
  emit("close");
};

const messages = ref([
  {
    type: "received",
    content: "欢迎使用AI助手！",
    timestamp: Date.now() - 60000,
  },
  {
    type: "mermaid",
    content: "请问有什么可以帮到您？",
    timestamp: Date.now(),
  }
]);

const newMessage = ref("");

function formatTime(timestamp) {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
}

const chatMessagesRef = ref(null);
// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
    }
  });
};

provide("scrollToBottom", scrollToBottom);

// 进入动画完成后的回调
const afterEnter = () => {
  scrollToBottom();
};

const isLoading = computed(() => {
  return messages.value.some((message) => message.loading);
});

const handleImgLoad = () => {
  scrollToBottom();
};

const sendMessage = async () => {
  const message = newMessage.value.trim();
  if (message) {
    messages.value.push({
      type: "sent",
      content: message,
      timestamp: Date.now(),
    });
    // 检查消息是否包含"分析产业"
    if (message.includes("产业分析")) {
      // 添加常规回复
      messages.value.push({
        type: "received",
        content: "正在为您分析产业情况，请稍等...",
        timestamp: Date.now(),
      });

      // 显示智能体卡片
      createAgentCards();
      newMessage.value = "";
      return;
    }

    // 合同分析
    if (message.includes("合同分析")) {
      messages.value.push({
        type: "received",
        content: "正在为您分析合同情况，请稍等...",
        timestamp: Date.now(),
      });
      messages.value.push({
        type: "mcp",
      });
      newMessage.value = "";
      return;
    }

    messages.value.push({
      type: "received",
      loading: true,
      timestamp: Date.now() + 500,
    });
    requestAnimationFrame(scrollToBottom);
    newMessage.value = "";

    try {
      const data = await chat({
        memoryId: 0,
        message,
      });
      // 判断data是否是GraphId，
      if (data.includes("GraphId")) {
        // 获取GraphId的值GraphId=1
        const map = {
          1: {
            key: "emp",
            content: "地图上只展示了公司",
          },
          2: {
            key: "project",
            content: "地图上只展示项目",
          },
          3: {
            key: "resource",
            content: "地图上只展示资源",
          },
          4: {
            key: "scope",
            content: "地图上只展示建筑",
          },
          5: {
            key: null,
            content: "地图上展示了全部",
          },
        };
        const graphId = data.split("GraphId=")[1].split("&")[0];
        companyStore.graphType = map[graphId].key;
        messages.value.at(-1).content = map[graphId].content;
      } else {
        // 不是GraphId
        messages.value.at(-1).content = data;
      }
      requestAnimationFrame(scrollToBottom);
    } catch (error) {
      console.log(error);

      messages.value.at(-1).content = "您的网络在开小差，请稍后再试";
    } finally {
      messages.value.at(-1).loading = false;
    }
  }
};

// 打开预览对话框
const chatPreviewDialogRef = ref(null);
const chatPreviewDialogVisible = ref(false);
const openChatPreviewDialog = (message) => {
  document.removeEventListener("keydown", handleKeyDown);
  chatPreviewDialogVisible.value = true;
  nextTick(() => {
    chatPreviewDialogRef.value.open(message);
  });
};

const closeChatPreviewDialog = () => {
  document.addEventListener("keydown", handleKeyDown);
  chatPreviewDialogVisible.value = false;
};

const mermaidDialogRef = ref(null);
const mermaidDialogVisible = ref(false);
const mermaidDialogType = ref(1);

const openMermaidDialog = (message) => {
  document.removeEventListener("keydown", handleKeyDown);
  mermaidDialogVisible.value = true;
  mermaidDialogType.value = message.typeTag;

  nextTick(() => {
    mermaidDialogRef.value.open(message);
  });
};

const closeMermaidDialog = () => {
  document.addEventListener("keydown", handleKeyDown);
  mermaidDialogVisible.value = false;
};

// agent测试数据
const agentData = [
  {
    name: "意图分析",
    type: "text",
    text: "正在为您分析产业情况，请稍等...",
  },
  {
    type: "search",
    name: "数据收集助手",
    isInitializing: true,
    messages: [
      { type: "mcp", text: "内部服务" },
      { type: "text", text: "内部服务 获取企业数据8条" },
      { type: "mcp", text: "外部数据" },
      { type: "text", text: "外部数据 【天眼查】 获取企业数据12条" },
      { type: "text", text: "数据收集结果: 已收集20条数据" },
    ],
  },
  {
    name: "数据分析智能体",
    type: "progress",
    number: 2,
    title: "数据分析进度",
    steps: [
      { text: "正在初始化...", active: false },
      { text: "正在分析...", active: true },
      { text: "分析完毕", pending: true },
    ],
  },

  {
    name: "数据汇总结果",
    type: "summary",
    // title: "汇总结果",
    count: 20,
    actionText: "点击查看详细内容",
    tag: "汇总结果",
  },
];

// 创建智能体卡片数据
const createAgentCards = () => {
  // 添加agent-cards消息，初始为空数组
  messages.value.push({
    type: "agent-cards",
    timestamp: Date.now(),
    agents: [],
  });

  // 依次添加各个agent卡片，每隔2秒添加一个
  agentData.forEach((agent, index) => {
    setTimeout(() => {
      messages.value[messages.value.length - 1].agents.push(agent);
      scrollToBottom();
    }, 2000 * (index + 1));
  });
};

defineExpose({
  openMermaidDialog,
});
</script>

<style scoped>
/* 动画样式 */
.animate-slide-in {
  animation: slideIn 0.3s cubic-bezier(0.22, 1, 0.36, 1);
}

.animate-slide-out {
  animation: slideOut 0.3s cubic-bezier(0.22, 1, 0.36, 1);
}

.animate-pulse-slow {
  animation: pulseSlow 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes slideOut {
  from {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
  to {
    opacity: 0;
    transform: translateY(30px) scale(0.9);
  }
}

@keyframes pulseSlow {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 消息动画 */
.message-enter-active {
  transition: all 0.3s ease-out;
}
.message-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}
.message-enter-from,
.message-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
